Skip to main content

管道 Pipe 是什么

Alternate text

一个可注入类 @Injectable() 可以使用 Pipe 完成输入输出参数的事前和事后处理。

  • 主要应用场景
    • 验证: 对输入数据进行验证,验证通过继续传递,否则抛出异常。
    • 转化: 将输入数据转化后输出。

数据校验实战

pnpm i class-validator class-transformer
src/main.ts
async function bootstrap() {
const app = await NestFactory.create(AppModule);

// 添加全局管道
app.useGlobalPipes(new ValidationPipe())

await app.listen(3000);
}
bootstrap();
create-user.dto.ts
import { ApiProperty } from "@nestjs/swagger";
import { IsNotEmpty, Matches, Max, Min, Length, IsEmail } from 'class-validator';

export class CreateUserDto {
@ApiProperty({ example: '18321312321' })
@Matches(/^1\d{10}$/g, { message: '请输入手机号' })
phoneNumber: string;

@ApiProperty({ example: '11111' })
@IsNotEmpty()
@Length(6, 10)
password: string;

@ApiProperty({ example: 'aa@qq.com' })
@IsEmail()
email: string;
}